#!/bin/sh /etc/rc.common
# Copyright (C) 2009-2010 OpenWrt.org

START=99
STOP=80

SERVICE_USE_PID=1

HAPROXY_BIN="/usr/sbin/haproxy"
HAPROXY_CONFIG="/etc/haproxy.cfg"
HAPROXY_PID="/var/run/haproxy.pid"

start() {
	service_start $HAPROXY_BIN -q -D -f "$HAPROXY_CONFIG" -p "$HAPROXY_PID"
	local COUNTER=0
	#添加主服务器
	iptables -t nat -D OUTPUT -j HAPROXY &> /dev/null
	iptables -t nat -X HAPROXY
	iptables -t nat -N HAPROXY
	iptables -t nat -F HAPROXY

	while true
	do	
		local server_ip=`uci get haproxy.@main_server[$COUNTER].server_ip 2>/dev/null`
		local server_name=`uci get haproxy.@main_server[$COUNTER].server_name 2>/dev/null`
		local server_port=`uci get haproxy.@main_server[$COUNTER].server_port 2>/dev/null`
		local server_weight=`uci get haproxy.@main_server[$COUNTER].server_weight 2>/dev/null`
		local validate=`uci get haproxy.@main_server[$COUNTER].validate 2>/dev/null`
		if [ -z "$server_ip" ] || [ -z "$server_name" ] || [ -z "$server_port" ] || [ -z "$server_weight" ]; then
			echo break
			break
		fi
		echo the main2 server $COUNTER $server_ip $server_name $server_port $server_weight
		[ "$validate" = 1 ] && {
			iptables -t nat -A HAPROXY -p tcp -d $server_ip -j ACCEPT
		}
		COUNTER=$(($COUNTER+1))
	done
	COUNTER=0
	#添加备用服务器
	while true
	do	
		local server_ip=`uci get haproxy.@backup_server[$COUNTER].server_ip 2>/dev/null`
		local server_name=`uci get haproxy.@backup_server[$COUNTER].server_name 2>/dev/null`
		local server_port=`uci get haproxy.@backup_server[$COUNTER].server_port 2>/dev/null`
		local validate=`uci get haproxy.@backup_server[$COUNTER].validate 2>/dev/null`
		if [ -z "$server_ip" ] || [ -z "$server_name" ] || [ -z "$server_port" ]; then
			echo break
			break
		fi
		echo the backup2 server $COUNTER $server_ip $server_name $server_port
		[ "$validate" = 1 ] && {
			iptables -t nat -A HAPROXY -p tcp -d $server_ip -j ACCEPT
		}
		COUNTER=$(($COUNTER+1))
	done

	iptables -t nat -I OUTPUT -j HAPROXY
}

stop() {
	kill -9 $(cat $HAPROXY_PID | tr "\n" " ")
	service_stop $HAPROXY_BIN
	iptables -t nat -D OUTPUT -j HAPROXY &> /dev/null
	iptables -t nat -F HAPROXY &> /dev/null
	sleep 1
	iptables -t nat -X HAPROXY &> /dev/null
}

reload() {
	$HAPROXY_BIN -D -q -f $HAPROXY_CONFIG -p $HAPROXY_PID -sf $(cat $HAPROXY_PID | tr "\n" " ")	
	#$HAPROXY_BIN -D -q -f $HAPROXY_CONFIG -p $HAPROXY_PID -sf $(cat $HAPROXY_PID)
}
